package com.ktjiaoyu.crm.service;

import com.ktjiaoyu.crm.dao.UserDao;
import com.ktjiaoyu.crm.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public Page<User> findPageByMap(Map param, Pageable pageable) {
        return userDao.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if(param.get("usrName")!=null){ //动态 SQL
                    predicates.add(cb.like(root.get("usrName"),"%"+param.get("usrName")+"%"));
                }
                if(param.get("roleId")!=null){
                    predicates.add(cb.equal(root.get("usrRoleId"),param.get("roleId")));
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        },pageable);
    }
}
